export namespace BlobReader {

  export async function readAsArrayBuffer(blob: Blob): Promise<string | ArrayBuffer | null | undefined> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = e => resolve(e.target!.result)
      reader.onerror = e => reject(e.target!.error)
      reader.readAsArrayBuffer(blob)
    })
  }

  export async function readAsDataURL(blob: Blob): Promise<string | ArrayBuffer | null | undefined> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = e => resolve(e.target!.result)
      reader.onerror = e => reject(e.target!.error)
      reader.readAsDataURL(blob)
    })
  }

  export async function readAsText(blob: Blob, encoding?: string | undefined): Promise<string> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = e => {
        if (typeof e.target?.result === 'string')
          resolve(e.target.result)
        else
          reject(new Error('Blob数据非文本'))
      }
      reader.onerror = e => reject(e.target!.error)
      reader.readAsText(blob, encoding)
    })
  }
}